package com.qst.survey.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qst.survey.entity.*;
import com.qst.survey.pojo.PageResult;
import com.qst.survey.pojo.Result;
import com.qst.survey.pojo.StatusCode;
import com.qst.survey.service.AdminService;
import com.qst.survey.service.UserService;
import com.qst.survey.util.JwtUtil;
import com.qst.survey.util.NoAuthorization;
import com.qst.survey.util.RedisUtils;
import com.qst.survey.vo.VM;
import com.qst.survey.vo.ViewDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Auther: IsAriel~~
 * @Date: 2021/3/17 13:39
 * @Description: 用户控制类
 */

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    RedisUtils redisUtils;

    /**
     * @param user: 用户对象
     * @return com.qst.survey.pojo.Result
     * @description: TODO 添加user方法
     * @date 13:52:41 2021/3/18
     */
    @NoAuthorization
    @PostMapping("/add/{checkCode}")
    public Result addUser(@RequestBody User user, @PathVariable String checkCode) {
        System.out.println(user + "==" + checkCode);
        String o = redisUtils.getCode(user.getEmail());
        if (o == null || !o.equals(checkCode)) {
            return new Result(false, StatusCode.ERROR, "验证码错误!");
        }
        boolean b = false;
        if (o != null && o.equals(checkCode)) {
            b = userService.addUser(user);
            if (b) {
                redisUtils.delete(user.getEmail());
                return new Result(true, StatusCode.OK, "注册成功");
            } else {
                return new Result(false, StatusCode.ERROR, "注册失败");
            }
        } else {
            return new Result(false, StatusCode.ERROR, "验证码失效!");
        }
    }

    /**
     * @param user    用户类
     * @param request 请求类
     * @return com.qst.survey.pojo.Result
     * @description TODO  用户登录
     * @date 2021/4/2
     */
    @NoAuthorization
    @PostMapping("/login")
    public Result loginUser(@RequestBody User user, HttpServletRequest request) {
        User user1 = userService.loginUser(user);
        if (user1 != null) {
            if (user1.getId() != null) {
                //密码是正确的
                //生成JWT令牌,返回到客户端
                Map<String, Object> info = new HashMap<>();
                info.put("username", user1.getUsername());
                info.put("userId", user1.getId());
                info.put("name", user1.getName());
                //基于工具类生产的jwt令牌,userid,登录的ip地址
                String jwt = JwtUtil.createJwt(user.getUsername(), request.getRemoteAddr(), null);
                info.put("token", jwt);
                String token = null;
                try {

                    token = redisUtils.getToken(user1.getUsername());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (token != null) {
                    redisUtils.delete(user1.getUsername());
                }
                redisUtils.setToken(user1.getUsername(), jwt);
                return new Result(true, StatusCode.OK, "登录成功", info);
            } else {
                return new Result(false, StatusCode.ERROR, "登录失败!");
            }
        }
        return new Result(false, StatusCode.ERROR, "登录失败!");
    }

    /**
     * @param email: 邮件
     * @return com.qst.survey.pojo.Result
     * @description: TODO 发送验证码接口
     * @date 16:40:44 2021/3/20
     */
    @NoAuthorization
    @PostMapping("/sendEmail/{email}")
    public Result sendEmail(@PathVariable String email) {
        int i = userService.sendEmailCode(email);
        if (i == 1) {
            return new Result(true, StatusCode.OK, "验证码已经发送!");
        } else {
            return new Result(true, StatusCode.ERROR, "验证码发送失败");
        }
    }

    /**
     * @param queryInfo ：分页数据类
     * @return com.qst.survey.pojo.Result
     * @description TODO   通过一个类来操作分页数据
     * @date 2021/4/2
     */
    @PostMapping("/findAll")
    public Result findAll(@RequestBody QueryInfo queryInfo) {
        Page page = new Page(queryInfo.getCurrent(), queryInfo.getSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        if (queryInfo.getQuery() != null && !queryInfo.getQuery().equals("")) {
            queryWrapper.like("username", queryInfo.getQuery());
        }
        page = userService.findAll(page, queryWrapper);
        PageResult<User> userPageResult = new PageResult<>(page.getTotal(), page.getRecords());
        return new Result(true, StatusCode.OK, "查询成功", userPageResult);
    }

    /**
     * @param user ：用户
     * @return com.qst.survey.pojo.Result
     * @description TODO 更新一个用户数据
     * @date 2021/4/2
     */
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user) {
        User user1 = userService.updateUser(user);
        if (user1 != null) {
            return new Result(true, StatusCode.OK, "修改成功", user1);
        } else {
            return new Result(false, StatusCode.ERROR, "修改失败", null);
        }

    }

    /**
     * @param id ：用户id
     * @return com.qst.survey.pojo.Result
     * @description TODO 通过id删除用户
     * @date 2021/4/2
     */
    @PostMapping("/removeUser/{id}")
    public Result removeUser(@PathVariable int id) {
        boolean flag = userService.removeUser(id);
        if (flag) {
            return new Result(true, StatusCode.OK, "删除成功", null);
        } else {
            return new Result(false, StatusCode.ERROR, "删除失败", null);
        }
    }

    /**
     * @param id 用户id
     * @return com.qst.survey.pojo.Result
     * @description TODO 通过用户id来查出一个用户
     * @date 2021/4/2
     */
    @PostMapping("/findOneById/{id}")
    public Result findOneById(@PathVariable int id) {
        User user = userService.findOneById(id);
        return new Result(true, StatusCode.OK, "删除成功", user);
    }

    /**
     * @param id 用户id
     * @return com.qst.survey.pojo.Result
     * @description TODO 通过用户id来找出所有用户回答的投票表
     * @date 2021/4/2
     */
    @PostMapping("/findUserReply/{id}")
    public Result findUserReply(@PathVariable int id) {
        ArrayList<UserReply> userReplies = userService.findUserReply(id);
        if (userReplies != null) {
            return new Result(true, StatusCode.OK, "查找成功", userReplies);
        } else {
            return new Result(false, StatusCode.OK, "查找失败", null);
        }
    }


}
